import ArrayUtil from '@/ArrayUtil';
import BaseUtil from '@/BaseUtil';
import BuffUtil from '@/BuffUtil';
import CameraUtil from '@/CameraUtil';
import ForceUtil from '@/ForceUtil';
import GameUtil from '@/GameUtil';
import HeroUtil from '@/HeroUtil';
import PlayerUtil from '@/PlayerUtil';
import TipFrameUtil from '@/TipFrameUtil';

export default class HeroDie {
    DB: Map<number, number> = new Map();
    constructor() {
        this.init();
        se.onUnitDeath(this.onUnitDeath.bind(this));
    }
    init() {
        let c = ForceUtil.getUserCount();
        for (let i = 0; i < c; i++) {
            this.DB.set(i, 15);
            PlayerUtil.addLumberState(Player(i), 15);
        }
    }
    onUnitDeath() {
        let u = GetTriggerUnit();
        if (IsUnitIllusionBJ(u)) return;
        if (IsUnitEnemy(u, Player(11))) {
            if (HeroUtil.isHero(u)) {
                TipFrameUtil.showIconTextOnUnit('ReplaceableTextures\\PassiveButtons\\PASBTNStatUp.blp', '-1', u);
                BuffUtil.clearUnitBuffs(u, true);
                let p = GetOwningPlayer(u);
                let t = this.DB.get(GetPlayerId(p));
                this.DB.set(GetPlayerId(p), t - 1);
                PlayerUtil.addLumberState(p, -1);
                let pn = GetPlayerName(p);
                let un = GetUnitName(u);
                if (t - 1 >= 0) {
                    PlayerUtil.message(`玩家 ${pn} 的英雄 ${un} 阵亡了,将于5秒后复活,复活次数剩余： ${t - 1}`);
                    BaseUtil.runLater(5, () => {
                        let { x, y } = ArrayUtil.randomElement(UIManager.UIChooseHero.model.spawnPos);
                        ReviveHero(u, x, y, false);
                        SetUnitManaPercentBJ(u, 100);
                        CameraUtil.moveCamera2unit(u, GetOwningPlayer(u), 1);
                    });
                } else {
                    PlayerUtil.message(`玩家 ${pn} 的英雄 ${un} 阵亡了,剩余复活次数为0，无法自动复活`);
                    let c = ForceUtil.getUserCount();
                    let end = 0;
                    for (let i = 0; i < c; i++) {
                        if (this.DB.get(i) <= 0) {
                            end++;
                        }
                    }
                    if (end == c) {
                        GameUtil.defeats();
                    }
                }
            } else {
                BuffUtil.clearUnitBuffs(u);
            }
        }
    }
}
